public class HashBuck {


    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;
    public double load_factor = 0.75;


    public HashBuck() {
        array = new Node[10];
    }

    public void put(int key,int val) {

        int index = key % array.length;
        //遍历链表
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //说明没有结束 -》开始头插法

        Node newNode = new Node(key, val);
        newNode.next = array[index];
        array[index] = newNode;
        this.usedSize++;

        //检查负载因子
        if(doFactor() >= load_factor) {
            //扩容
            grow();
        }
    }

    private void grow() {
        Node[] newArray = new Node[2* array.length];
        //遍历原来的数组
        for (int i = 0; i < array.length; i++) {
            //每一个下标都是一个链表
            Node cur = array[i];
            while (cur != null) {
                //确定当前key在新的桶当中的位置
                int newIndex = cur.key%newArray.length;
                //接下来需要把cur这个节点 放到新的桶当中的newIndex位置
                //采用头插法
                Node curNext = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curNext;
            }
        }
        this.array = newArray;
    }

    private double doFactor() {
        return usedSize*1.0/ array.length;
    }


    public int get(int key) {
        int index = key % array.length;
        //遍历链表
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
